import api from '../../../utils/api'
import dateTimePicker from './dateTimePicker';
import uploadOss from '../../../utils/uploadFileOss/index'
import util, { setUserInfo } from '../../../utils/util'
import { cloneDeep } from '../../utils/util'
import qrapi from '../../../api/index';
import CONFIG from '../../../utils/config';

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
    pageName: '我的健康/档案详情',
    data: {
        defaultAvatarUrl,
				countdown: 60,
				countdownInterval: null,
        showModalCard: false,
        password: '',
        isFocus: false,
        inputPwd: true,
        inputNum: 0,
        passwordFirst: '',
        passwordTwo: '',
        basicHidden: false,
        dialogHidden: true,
        qrcodeHidden: true,
        ll: null,
				phoneshow: false,
				editPhoneNumber: '',
				verifcode: '',
				disableVerifcode: false,
        list: {
            nickname: null
        },
				verifcodeText: '发送验证码',
        isGender: false,//性别显隐
        startT: '',
        birthday: '',
        itemList: ['已婚', '未婚'],
        array: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
        index: 0,
        eatValue: [],
        eatflag: false,
        guominArr: [{
            name: '是',
            checked: false
        }, {
            name: '否',
            checked: false
        }],
        guominValue: [],
        guominflag: false
    },
    onReady() {

    },
		/**
   * 生命周期函数--监听页面卸载
   */
		onUnload() {
			if(this.data.countdownInterval) {
				clearInterval(this.data.countdownInterval);
			}
		},
    onLoad(options) {
        if (options) {
            if (options.type) {
                console.log('5555');
                if (options.type == 1) {
                    this.setData({
                        basicHidden: false,
                        dialogHidden: true
                    });
                    // this.data.basicHidden =  false
                    // this.data.dialogHidden =  true
                } else {
                    console.log('666');
                    this.setData({
                        basicHidden: true,
                        dialogHidden: false
                    });
                }
            }
            if (options.histroyPage) {
                if (options.histroyPage == 'myHealth') {
                    this.setData({
                        qrcodeHidden: true
                    });
                }
            }
        }
        this.getuserinfo()
    },
    getuserinfo() {
        // 整体列表查询
        try {
            api.post('/api/hxhealth/user/load').then((res) => {
                // console.log(res);
                console.log('----res----', res[0])
                setUserInfo(res[0])
                if (!res[0].birthday || res[0].birthday == '') {
                    let userInfo = wx.getStorageSync('userInfo');
                    let list = res[0]
                    console.log(userInfo.birthday)
                    if (userInfo.birthday) {
                        list.birthday = userInfo.birthday
                        console.log(list, '1');
                        this.changeList(list, 1)
                    }
                }
                if (!res[0].gender || res[0].gender == '') {
                    let userInfo = wx.getStorageSync('userInfo');
                    let list = res[0]
                    console.log(userInfo.gender)
                    if (userInfo.gender) {
                        list.gender = userInfo.gender
                        console.log(list, '1');
                        this.changeList(list, 1)
                    }
                }
                if (res[0].height && res[0].weight) {
                    let height = parseInt(res[0].height) / 100 || 0
                    res[0].bmi = (Number(res[0].weight) / (height * height)).toFixed(0)
                    res[0].height = (Number(res[0].height)).toFixed(1)
                    res[0].weight = (Number(res[0].weight)).toFixed(1)
                }
                this.setData({
                    list: res[0],
                    birthday: res[0].birthday,
                    startT: res[0].birthday,
                });
            })
        } catch (e) {
            console.error(e)
        }
        // 生日回显
        if (this.data.birthday !== '') {
            console.log(this.data.birthday);
            var start = this.data.birthday
            var obj = dateTimePicker.dateTimePicker(1935, 2020, start);
            this.setData({
                dateTime: obj.dateTime,
                dateTimeArray: obj.dateTimeArray
            });
            var startT = dateTimePicker.formatPickerDateTime(this.data.dateTimeArray, this.data.dateTime)
            this.setData({
                startT: startT
            })
        } else {
            const start = ''
            const obj = dateTimePicker.dateTimePicker(1935, 2020, start);
            this.setData({
                dateTime: obj.dateTime,
                dateTimeArray: obj.dateTimeArray
            });
            // var startT = dateTimePicker.formatPickerDateTime(this.data.dateTimeArray, this.data.dateTime)
            this.setData({
                startT: ''
            })
        }
      },
    onChooseAvatar(e) {
        console.log(e);
        var num = []
        num.push(e.detail.avatarUrl)
        console.log(num);
        console.log(num);
        this.uploadDIY(
            num,
            0,
            0,
            0,
            num.length,
            num
        )
    },
    uploadDIY(filePaths, successUp, failUp, i, length, param) {
      // 正在上传
      // debugger
      param.doing = true // this.data.prove.doing = true;
      param.imagesUrl = []
      let that = this
      // wx.showLoading({
      //     title: `上传${i}/${length}张图片中`,
      //     duration: 1000
      // })
    
      uploadOss(filePaths[i])
          .then((res) => {
              successUp++
              i++
              param.imagesUrl.push(res.url)
              // that.setData({
              //     prove: that.data.prove
              // })
              if (i === length) {
                  // 全部上传成功
                  console.log('图片上传成功后的url', param.imagesUrl, length)
                  if (successUp === length) {
                      param.uploadSuccess = true
                      console.log('图片上传成功进入回调')
                      // wx.hideLoading()
                      that.savetmp(param.imagesUrl[0])
                  } else {
                      // 图片上传部分失败
                      param.doing = false
                      wx.hideLoading()
                      wx.showToast({
                          title: '上传图片失败,请重新上传！',
                          icon: 'none',
                          duration: 2000
                      })
                  }
              } else {
                  // 递归调用uploadDIY函数
                  that.uploadDIY(
                      filePaths,
                      successUp,
                      failUp,
                      i,
                      length,
                      param
                  )
              }
          })
          .catch((e) => {
              console.log('---图片上传失败 catch--- e', e)
              param.doing = false
              failUp++
              wx.hideLoading()
              wx.showToast({
                  title: '图片上传失败，请重新上传！',
                  icon: 'none',
                  duration: 2000
              })
          })
    },
    savetmp(e) {
      console.log(e);
      let userInfo = wx.getStorageSync('userInfo');
      userInfo.wechatimg = e
      this.saveUserInfo(userInfo, false)
      // app.getHttpUser()
    },
    saveUserInfo(data = {}) {
      return new Promise((resolve, reject) => {
          api.post('/api/hxhealth/user/save', {
              data: data,
          }).then(res => {
                wx.showToast({
                    title: '修改成功',
                    icon: 'none'
                })
                this.getuserinfo() 
              resolve(res)
          }).catch(e => {
              reject(e)
          })
      })
    },
    handleModelValue(e) {
        let value = e.detail.value
        let model = e.target.dataset.model
        this.setData({
            [model]: value
        })
    },
    // 修改生日缓存
    bindBirthdayChange(event) {
        console.log('进来');
        console.log(event);
        // api.post('/api/hxhealth/user/save', {
        //     data: { birthday: event }
        // }).then(() => {
        //     let userInfo = wx.getStorageSync('userInfo');
        //     userInfo.birthday = event
        //     wx.setStorageSync('userInfo', userInfo)
        //     wx.showToast({
        //         title: '修改成功',
        //         icon: 'none'
        //     })
        // }).catch(e => {
        //     console.log('error', e)
        // })
    },
    //获取时间日期并修改
    changeDateTime(e) {
        console.log(e.detail.value);

        this.setData({
            dateTime: e.detail.value
        })
        // let startT = dateTimePicker.formatPickerDateTime(this.data.dateTimeArray, this.data.dateTime)
        // this.setData({
        //     startT: startT
        // })
        this.data.list.birthday = this.data.dateTime
        this.bindBirthdayChange(this.data.startT)
        this.changeList(this.data.list)

    },
    // 修改身高
    bindblurHeight(e) {
        console.log(e.detail.value);
        let val = e.detail.value;
        if (val.length <= 50 && val.length > 0 && this.data.list.height !== val) {
            console.log('合规', val.length, this.data.list);
            this.data.list.weight = Math.round(this.data.list.weight)
            let that = this
            that.data.list.height = Math.round(val)
            that.changeList(that.data.list)
            // wx.showModal({
            //     title: '提示',
            //     content: '是否修改身高为' + val + 'cm',
            //     success: function (res) {
            //         if (res.confirm) {
            //             console.log('用户点击确定')
            //             that.data.list.height = Math.round(val)
            //             that.changeList(that.data.list)
            //         }
            //         if (res.cancel) {
            //             console.log('用户点击取消')
            //         }
            //     }
            // })
        } else {
            console.log('不合规', val.length);
            wx.showToast({
                title: '添加失败',
                icon: 'none'
            })
            this.onLoad()
        }
        // this.$apply();
    },
    // 修改体重
    bindblurWeight(e) {
        console.log(e.detail.value);
        let val = e.detail.value;
        if (val.length <= 350 && val.length > 0 && this.data.list.weight !== val) {
            console.log('合规', val.length, this.data.list);
            this.data.list.height = Math.round(this.data.list.height)
            let that = this
            that.data.list.weight = Math.round(val)
            that.changeList(that.data.list)
            // wx.showModal({
            //     title: '提示',
            //     content: '是否修改体重为' + val + 'kg',
            //     success: function (res) {
            //         if (res.confirm) {
            //             console.log('用户点击确定')
            //             that.data.list.weight = Math.round(val)
            //             that.changeList(that.data.list)
            //         }
            //         if (res.cancel) {
            //             console.log('用户点击取消')
            //         }
            //     }
            // })
        } else {
            console.log('不合法', val.length);
            wx.showToast({
                title: '添加失败',
                icon: 'none'
            })
        }
        // this.$apply();
    },
    // 修改列表
    changeList(a, b) {
        try {
            let data = a
            console.log('data', data);
            api.post('/api/hxhealth/user/save', {
                data:data
            }).then((res) => {
                console.log('----saveMobile----');
                console.log(res)
                if (b !== 1) {
                    wx.showToast({
                        title: '修改成功',
                        icon: 'none',//当icon：'none'时，没有图标 只有文字
                        duration: 2000
                    })
										this.setData({
											phoneshow: false
										})
                }
                this.onLoad()
            }).catch((error) => {
							wx.showToast({
								title: error.faultstring,
								icon: 'none',
								duration: 3000
							});
							return;
						});
        } catch (e) {
            console.error(e)
            wx.showToast({
                title: e.faultstring,
                icon: 'none',//当icon：'none'时，没有图标 只有文字
                duration: 2000
            })
        }
    },
    downImg() {
        wx.showLoading({
            title: '下载中'
        })
        util.downHttpImg(this.data.qrCode).then(res => {
            console.log('dflsjflksjfkljslkf', res);
            wx.hideLoading()
        }).catch(() => {
            wx.hideLoading()
        })
    },
    changeYL: function () {
        this.setData({
            showModal: true
        })
    },
    /**
     * 隐藏模态对话框showModal1
     */
    hideModal: function () {
        this.setData({
            showModal: false
        });
    },
    // 修改职业失去焦点
    bindblurProfession(e) {
        console.log(e.detail.value);
        let val = e.detail.value;
        if (val.length <= 50 && val.length >= 0 && this.data.list.profession !== val) {
            console.log('合规', val.length, this.data.list);
            let that = this
            that.data.list.profession = val
            that.changeList(that.data.list)
        } else {
            console.log('不合法', val.length);
        }
        var nickname = e.currentTarget.dataset.nickname;
        // this.$apply();
    },
    validateNumber(val) {
        return val.replace(/\D/g, '')
    },
    toShowModalCard(e) {
        this.setData({
            showModalCard: true
        })
    },
    hideModalCard() {
        this.setData({
            showModalCard: false
        });
    },
    getFocus() {
        this.setData({
            isFocus: true
        })
    },
    changeNmuberVip() {
        this.toShowModalCard()
    },
    pwd(e) {
        console.log(e.detail.value)
        // let reg = /[^\d]/g
        // let number = e.detail.value.replace(reg, '')
        let number = e.detail.value
        this.setData({
            numberVip: number
        })
        return number
    },
    sure() {
        this.setData({
            'list.cardnumber': this.data.numberVip
        })
        console.log(this.data.list.cardnumber);
        if (this.data.list.cardnumber && this.data.list.cardnumber.length >= 6) {
            this.changeList(this.data.list)
            this.hideModalCard()
            this.setData({
                numberVip: null
            })
        } else {
            wx.showToast({
                icon: 'none',
                title: '请输入正确的卡号',
            })
        }
    },
    // 修改家庭住址失去焦点
    bindblurAddress(e) {
        // console.log(e.detail.value);
        let val = e.detail.value;
        if (val.length <= 50 && val.length >= 3 && this.data.list.address !== val) {
            // console.log('合规', val.length, this.data.list);
            this.data.list.address = val
            this.changeList(this.data.list)
        } else if (val.length > 18) {
            console.log('大于18', val.length);
        } else {
            console.log('不合法', val.length);
        }
        // this.$apply();
    },
    haha(e) {
        let data = {
            username: e
        }
        api.post('/api/hxhealth/user/save', {
            data: data
        }).then(res => {
        }).catch(e => {
            wx.Toast({
                title: '储存失败',
                icon: 'none'
            })
        })
    },
    // 修改姓名失去焦点
    bindblur(e) {
        // console.log(e.detail.value);
        let val = e.detail.value;
        if (val.length <= 10 && val.length > 0 && this.data.list.nickname !== val) {
            // console.log('合规', val.length, this.data.list);
            this.setData({
                'list.nickname':val
            }, () => {
                this.changeList(this.data.list)
                // this.haha(this.data.list.nickname)
            })
        } else if (val.length > 10) {
            console.log('大于5', val.length);
            wx.showToast({
                title: '添加失败,不合法',
                icon: 'none'
            })
        } else {
            console.log('不合法', val.length);
            wx.showToast({
                title: '添加失败',
                icon: 'none'
            })
        }
    },
		// 发送验证码
		getVerifcode() {
			if(this.data.disableVerifcode) {
				return
			}
			const phoneNumberRegex = /^1[3456789]\d{9}$/;
			if(!this.data.editPhoneNumber) {
				wx.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return
			}
			if(!phoneNumberRegex.test(this.data.editPhoneNumber)) {
				wx.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}
			this.getQrCode()
		},
		getQrCode() {
			const actions = {
				data: {
					account: this.data.editPhoneNumber
				}
			};
			qrapi
				.post(`/api/hxhealth/login/mobilecode/${CONFIG.orgCode}/${CONFIG.appCode}`, actions, true)
				.then((res) => {
					console.log('===========发送验证码成功=========================');
					this.setData({
						disableVerifcode: true
					})
					this.startCountdown();
				})
				.catch((error) => {
					wx.showToast({
						title: error.faultstring,
						icon: 'none',
						duration: 3000
					});
					return;
				});
		},
		startCountdown () {
			this.setData({
				countdown: 60,
				countdownInterval: setInterval(this.updateCountdown, 1000)
			});
		},
		
		updateCountdown () {
			let countdown = this.data.countdown - 1;
			let verifcodeText = countdown + 's';
			
			if (countdown <= 0) {
				clearInterval(this.data.countdownInterval);
				this.setData({
					disableVerifcode: false,
					verifcodeText: '发送验证码'
				});
			} else {
				this.setData({
					countdown: countdown,
					verifcodeText: verifcodeText
				});
			}
		},
    // 修改绑定手机号
    isMiddle(e) {
        console.log('==========修改手机号==========================');
        this.setData({
					editPhoneNumber: this.data.list.mobile,
          phoneshow: true
        })
    },
		closePhoneEdit() {
			this.setData({
				phoneshow: false
			})
		},
		onChangePhone(e) {
			this.setData({
				editPhoneNumber: e.detail,
			})
		},
		onChangeVerifcode(e) {
			this.setData({
				verifcode: e.detail,
			})
		},
		// 保存修改的手机号
		savePhone(e) {
			const data = cloneDeep(this.data.list)
			const phoneNumberRegex = /^1[3456789]\d{9}$/;
			if(!this.data.editPhoneNumber) {
				wx.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return
			}
			if(!phoneNumberRegex.test(this.data.editPhoneNumber)) {
				wx.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}
			if(!this.data.verifcode) {
				wx.showToast({
					title: '请输入验证码',
          icon: 'none'
				})
				return
			}
			data.mobile = this.data.editPhoneNumber
			data.verifcode = this.data.verifcode
			this.changeList(data)
		},
    bindMobileSuccess(e) {
        console.log('获取手机号成功');
        // 延迟登陆
        setTimeout(() => {
            console.log(wx.getStorageSync('mobile'), '获取手机号')
            this.setData({
                'list.mobile': wx.getStorageSync('mobile')
            })
            this.setData({
                'mobileModal.show': false
            })
            this.changeList(this.data.list)
        }, 1500)

    },
    // 修改性别缓存
    bindGenderChange(event) {
        console.log(event);
        api.post('/api/user/savenickname', {
            data: { gender: event }
        }).then(res => {
            let userInfo = wx.getStorageSync('userInfo');
            userInfo.gender = event
            wx.setStorageSync('userInfo', userInfo)
            wx.showToast({
                title: '修改成功',
                icon: 'none'
            })
        }).catch(e => {
        })
    },
    //控制性别的显隐
    isGender: function () {
        let listnum = this.data.list
        var ithis = this;
        wx.showActionSheet({
            itemList: ['男', '女'],
            success(res) {
                console.log(res.tapIndex)
                console.log('列表', ithis.data.list.gender);
                if (ithis.data.list.gender !== '' && res.tapIndex == 1) {
                    listnum.gender = 2
                    ithis.setData({
                        list: listnum
                    })
                    ithis.changeList(listnum, 1)
                } else if (ithis.data.list.gender !== '' && res.tapIndex == 0) {
                    // let that = this
                    listnum.gender = 1
                    ithis.setData({
                        list: listnum
                    })
                    ithis.changeList(listnum)
                } else if (ithis.data.list.gender == '' && res.tapIndex !== '') {
                    if (res.tapIndex == 0) {
                        listnum.gender = 1
                        ithis.setData({
                            list: listnum
                        })
                        ithis.changeList(listnum)
                    } else if (res.tapIndex == 1) {
                        listnum.gender = 2
                        ithis.setData({
                            list: listnum
                        })
                        ithis.changeList(listnum)
                    }
                }
                ithis.bindGenderChange(ithis.data.list.gender)
            },
            fail(res) {
                console.log(res.errMsg)
            }
        })
    }  
})
